/*
 * 
 */
package controllers;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.logging.Level;
import models.Artist;
import models.Release;
import models.ReleaseImg;
import play.Logger;

public class Discogs {

	static void setArtistInfo(Artist a) {
		try {
			Reader r = connect("http://api.discogs.com/database/search?type=artist&q=" + spaceToPlus(a.name));
			JsonParser jp = new JsonParser();
			JsonElement j = jp.parse(r);
			JsonArray results = j.getAsJsonObject().getAsJsonArray("results");
			if (results.size() == 0)
				return;
			JsonObject elem = results.get(0).getAsJsonObject();
			j = jp.parse(connect(elem.getAsJsonPrimitive("resource_url").getAsString()));
			elem = j.getAsJsonObject();
			if (elem.get("profile") != null)
				a.popis = makeLinks(elem.get("profile").getAsString());
			if (elem.get("images") != null) {
				JsonArray imgs = elem.get("images").getAsJsonArray();
				if (imgs.size() == 0) {
					return;
				}
				a.image = imgs.get(0).getAsJsonObject().get("uri150").getAsString();
			}
			a.save();
		} catch (IOException ex) {

		}
	}
	
	static void setReleaseInfo(Release a) {
		try {
			String query = "http://api.discogs.com/database/search?artist="
					+ spaceToPlus(a.artist.name) + "&release_title=" + spaceToPlus(a.name)
					+ "&type=release";
			Reader r = connect(query);
			JsonParser jp = new JsonParser();
			JsonElement j = jp.parse(r);
			JsonArray results = j.getAsJsonObject().getAsJsonArray("results");
			if (results.size() == 0)
				return;
			JsonObject elem = results.get(0).getAsJsonObject();
			j = jp.parse(connect(elem.getAsJsonPrimitive("resource_url").getAsString()));
			elem = j.getAsJsonObject();
			if (a.images == null)
				a.images = new LinkedList<ReleaseImg>();
			ReleaseImg ri = new ReleaseImg();
			if (elem.get("images") == null)
				return;
			JsonArray imgs = elem.get("images").getAsJsonArray();
			if (imgs.size() == 0)
				return;
			ri.url = imgs.get(0).getAsJsonObject().get("uri150").getAsString();
			a.images.add(ri);
			a.save();
		} catch (IOException ex) {

		}
	}

	static Reader connect(String urls) throws IOException {
			URL url = new URL(urls);
			URLConnection conn = url.openConnection();
			conn.setRequestProperty("User-Agent", "Nightingale +evening-sunset.herokuapp.com");
			conn.setRequestProperty("Accept-Encoding", "gzip");
			return new InputStreamReader(conn.getInputStream());
	}

	static String spaceToPlus(String s) {
		return s.replaceAll("[\\s]+", "+");
	}

	private static String makeLinks(String popis) {
		return popis.replaceAll("\\[a=([^\\]]*)\\]", "<a href=\"#search/artist/0/$1\">$1</a>");
	}
}
